package cn.uway.shiro;

import java.util.Collection;
import java.util.Set;

import org.apache.shiro.cache.CacheException;

import cn.uway.cache.RedisCache;

public class JedisShiroCache<K,V> implements ICache<K,V> {
	
    private RedisCache  redisClient;
	
	private String keyPrefix = "shiro_redis_cache:";
	
	public String getKeyPrefix() {
		return keyPrefix;
	}

	public void setKeyPrefix(String keyPrefix) {
		this.keyPrefix = keyPrefix;
	}
	
	public JedisShiroCache(RedisCache  redisClient) {
	     this.redisClient = redisClient;
	}
	
	public JedisShiroCache(RedisCache  redisClient, String prefix) {			
		this.redisClient = redisClient;		
		this.keyPrefix = prefix;
	}
	  
     
    @SuppressWarnings("unchecked")
	@Override  
    public V get(K key) throws CacheException {  
    	return (V)redisClient.getObject(this.keyPrefix+key.toString() );
    }  
  
    @SuppressWarnings("unchecked")
    @Override  
    public V put(K key, V value) throws CacheException {  
        return (V)redisClient.putObject(this.keyPrefix+key.toString(), value);  
    }  
    
    @SuppressWarnings("unchecked")
    @Override
	public V put(K key, V value, int expireSeconds) throws CacheException {
    	 return (V)redisClient.putObject(this.keyPrefix+key.toString(), value, expireSeconds);  
	}  
  
  
    @SuppressWarnings("unchecked")
    @Override  
    public V remove(K key) throws CacheException {  
    	return (V)redisClient.removeObject(this.keyPrefix+key.toString()); 
    }  
    
  
    @Override  
    public int size() {  
        if (keys() == null)  {
        	 return 0;  
        }           
        return keys().size();  
    }  
  
    @SuppressWarnings("unchecked")
    @Override  
    public Set<K> keys() {         
        return  (Set<K>)redisClient.getKeys(this.keyPrefix + "*");  
    }  
  
    @SuppressWarnings("unchecked")
    @Override  
    public Collection<V> values() {  
        return  (Collection<V>)redisClient.getValues(this.keyPrefix + "*");  
    }  
    
    @Override  
    public void clear() throws CacheException {  
    	redisClient.clear(this.keyPrefix + "*");
    }

	
   
}
